#include "CLogger.h"

namespace onet
{

CLogger::CLogger()
{
    logToFile = false;

    this->setType(ELMT_Error, "Error");
    this->setType(ELMT_Info, "Info");
    this->setType(ELMT_User, "User");
    this->setType(ELMT_Warning, "Warning");
}

//! Set the name of a message type
//! Can overwrite old names!
void CLogger::setType(u16 type, std::string name)
{
    types[type] = name;
}

bool CLogger::log(u16 type, std::string str)
{
    std::map<u16,std::string>::iterator it = types.find(type);

    if(it == types.end())
        return false;

     std::string s = types[type];

    time_t now;
    time(&now);
    char buf[128];
    strftime(buf, 128, "%d.%m %H:%M:%S", localtime(&now));

    if(logFile && logToFile)
    {
        logFile << "[" << buf << "-" << s.c_str() << "]" << str.c_str() << std::endl;
    }

    std::cout << "[" << buf << "-" << s.c_str() << "]" << str.c_str() << std::endl;

    return true;
}

CLogger::~CLogger()
{
    //! Dont forget to close the file :)
    logFile.close();
}

bool CLogger::setLogFile( std::string str )
{
    logFile.open(str.c_str(), std::ios_base::trunc);

    //! We couldn't open the file?
    if(!logFile.is_open())
    {
        logToFile = false;
        this->log(ELMT_Warning, "Could not open log file");

        return false;
    }

    logToFile = true;
    return true;
}

void CLogger::setLogToFile( bool b )
{
    logToFile = b;
}

bool CLogger::isLoggingToFile()
{
    return logToFile;
}

} //! end namespace onet
